package com.googlecode.sparda.commons.adapter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;

/**
 * A set of utility to use a {@link String} based approach.
 * @author Fabio Grucci (<i>alias</i> <b>Phoenix</b>)
 * @version 0.0.1
 * @since 0.0.1
 */
public final class StringAdapter {
	
	private StringAdapter() {/* Utility class */}
	
	/**
	 * Methods that create an {@link InputStream} from a collection of {@link String}.
	 * @param stringCollection The {@link Collection} of {@link String} to convert in {@link InputStream}
	 * @return The {@link InputStream} result of concatenation of the string
	 */
	public static InputStream toStream(Collection<String> stringCollection) {
		return toStream(stringCollection.toArray(new String[0]));
	}

	/**
	 * Methods that create an {@link InputStream} from a collection of {@link String}.
	 * @param strings The {@link String} array to convert in {@link InputStream}
	 * @return The {@link InputStream} result of concatenation of the string
	 */
	public static InputStream toStream(String... strings) {
		StringBuilder s = new StringBuilder();
		for(String string : strings)
			s.append(string).append("\n");
		return new ByteArrayInputStream(s.toString().getBytes());
	}

	/**
	 * Methods that create an {@link InputStream} from a collection of {@link String}.
	 * The collection must be composed by key value element.
	 * @param stringCollection The {@link Collection} of {@link String} 
	 * 								to convert in a properties {@link InputStream}
	 * @return The {@link InputStream} result of concatenation of the "key = value" {@link String}
	 */
	public static InputStream toPropertiesStream(Collection<String> stringCollection) {
		return toStream(stringCollection.toArray(new String[0]));
	}

	/**
	 * Methods that create an {@link InputStream} from an array of {@link String}.
	 * The collection must be composed by key value element.
	 * @param keyValueStrings The {@link String} array to convert in a properties {@link InputStream}
	 * @return The {@link InputStream} result of concatenation of the "key = value" {@link String}
	 */
	public static InputStream toPropertiesStream(String... keyValueStrings) {
		if(keyValueStrings.length%2 != 0)
			throw new IllegalArgumentException("The key Value properties cannot be odd");
		StringBuilder s = new StringBuilder();
		for(int i=0; i<keyValueStrings.length; i+=2) {
			String key = keyValueStrings[i];
			String value = keyValueStrings[i + 1];
			s.append(key).append(" = ").append(value).append("\n");
		}
		return new ByteArrayInputStream(s.toString().getBytes());
	}
}
